package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void deduction(Long id, Long amount) {
        //1.查询用户
        User user = userMapper.selectById(id);

        //2.判断状态
        if (user == null || user.getStatus() == UserStatus.FREEZE){
            throw new RuntimeException("用户状态异常");
        }
        //3.判断金额
        if (user.getBalance() < amount) {
            throw new RuntimeException("用户余额不足");
        }
        //4.扣减余额
//        userMapper.deduction(id,amount);
//        update user set balance = #{balance} ,status = #{status} where id = #{id}
        long remainBalance = user.getBalance() - amount;
        this.lambdaUpdate()
                .set(User::getBalance,remainBalance) //更新余额
                .set(remainBalance == 0,User::getStatus,2) //动态判断，是否跟新status
                .eq(User::getId,id)
                .eq(User::getBalance,user.getBalance()) //乐观锁
                .update();

    }

    @Override
    public UserVO queryUserAndAddressById(Long id) {
        //查询用户
        User user = getById(id);
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);

        //根据用户id查询用户的收货地址列表
        List<Address> addressList = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, id)
                .list();
        userVO.setAddresses(BeanUtil.copyToList(addressList, AddressVO.class));

        return userVO;
    }

    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
        //1.找出用户列表
        List<User> userList = this.listByIds(ids);
        List<UserVO> userVOS = BeanUtil.copyToList(userList, UserVO.class);
        //2.根据用户id集合查询用户的收货地址列表，并转换为map， 用户id为key,地址列表为value
        List<Address> addressList = Db.lambdaQuery(Address.class)
                .in(Address::getUserId, ids)
                .list();
        Map<Long, List<AddressVO>> addressVoMap = BeanUtil.copyToList(addressList, AddressVO.class).stream().collect(Collectors.groupingBy(AddressVO::getUserId));

        //3.回填用户列表的地址列表
        for (UserVO userVO : userVOS) {
            userVO.setAddresses(addressVoMap.get(userVO.getId()));
        }
        return userVOS;
    }
}
